<template>
  <div id="top-container">
    <p>
      <a @click="goBack">&lt; 返回</a>
      <input name="author" type="text" style="display: none" />
      <a class="submit-article" @click="SubitArticle">发布文章</a>
    </p>
  </div>
  <div style="border-bottom: 1px solid #e8e8e8">
    <div id="editor-toolbar"></div>
  </div>
  <div id="content">
    <div id="editor-container">
      <div id="title-container">
        <input placeholder="请输入文章标题" autocomplete="off" />
      </div>
      <div id="editor-text-area"></div>
    </div>
  </div>
</template>

<script>
  import router from "@/router/index.js";
  import "@/assets/css/wangedit.css";
  import "@/assets/js/wangedit.js";
  import { onMounted } from "vue";
  import { useUserStore } from "@/store/user.js";
  import { CreateArticle } from "../../api/ArticleApi";
  export default {
    setup() {
      const userStore = useUserStore();
      console.log(userStore.userInfo);
      const goBack = () => {
        router.go(-1);
      };
      onMounted(() => {
        let article;
        // 获取标题
        const title = document.querySelector("#title-container input");
        // // 创建文章数据
        if (localStorage.getItem("article") == null) {
          localStorage.setItem(
            "article",
            JSON.stringify({
              title: "",
              content: "",
              contentPreview: "",
              author: "",
            })
          );
        } else {
          article = JSON.parse(localStorage.getItem("article"));
        }
        // 通用防抖
        function debounce(func, wait) {
          let timeout;
          return function () {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => {
              func.apply(context, args);
            }, wait);
          };
        }

        // 监听输入
        title.addEventListener(
          "input",
          debounce(function () {
            // 更新 article 对象
            // 将标题中的特殊字符替换为空
            title.value = title.value.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, "");
            // 限制标题长度 如果标题长度超过20个字符，截取前20个字符
            if (title.value.length > 20) {
              alert("文章标题长度不能超过20个字符！");
              title.value = title.value.substring(0, 15);
            }
            article["title"] = title.value;
            console.log("===标题更新===");
            console.log(article);
            // 将内容存储到本地
            localStorage.setItem("article", JSON.stringify(article));
            console.log(title.value);
          }, 500)
        );

        // 页面加载时，从本地获取标题
        // JSON.parse 字符串 转 对象
        function writeTitle() {
          title.value = JSON.parse(localStorage.getItem("article"))["title"]
            ? JSON.parse(localStorage.getItem("article"))["title"]
            : "";
          console.log("===页面加载===");
        }
        writeTitle();
        // 编辑器部分
        const E = window.wangEditor;
        // 切换语言
        const LANG = location.href.indexOf("lang=en") > 0 ? "en" : "zh-CN";
        E.i18nChangeLanguage(LANG);

        // 编辑器配置
        const editorConfig = {
          placeholder: "请输入文章内容",
          scroll: false, // 禁止编辑器滚动
          // MENU_CONF: {
          //   uploadImage: {
          //     fieldName: "your-fileName",
          //     base64LimitSize: 10 * 1024 * 1024, // 10M 以下插入 base64
          //   },
          // },
          // 编辑区域发生变化时，将内容写入本地
          onChange: debounce(function (editor) {
            console.log("===编辑器内容跟新===");
            const html = editor.getHtml();
            console.log(html);

            // 文章内容预览
            // 截取到文章前76个字符
            // 将换行符替换为空格
            const contentPreview = editor
              .getText()
              .substring(0, 120)
              .replace(/[\r\n]/g, " ");
            console.log("===纯文本信息===");
            console.log(contentPreview);

            // 更新 article 对象
            // article["title"] = title.value;
            article["content"] = html;
            article["contentPreview"] = contentPreview;
            // 文章作者
            article["author"] = userStore.userInfo.username;
            // article["contentPreview"] = contentPreview;
            // 将内容存储到本地
            // localstorage 只能保存字符串类型数据,不能保存对象
            // 所以要通过JSON.stringify将对象转换为字符串
            localStorage.setItem("article", JSON.stringify(article));
          }, 500),
        };

        // 先创建 editor
        const editor = E.createEditor({
          selector: "#editor-text-area",
          content: [],
          // 从本地获取文章内容
          html: JSON.parse(localStorage.getItem("article"))["content"],
          // html: '',
          config: editorConfig,
        });

        // 工具栏配置
        const toolbarConfig = {
          // "group-image", "group-video"
          // 去除 引用 插入连接 插入图片 插入视频 插入表格 插入代码块
          excludeKeys: [
            "blockquote",
            "insertLink",
            "group-image",
            "group-video",
            "insertTable",
            "insertVideo",
            "codeBlock",
          ],
        };

        // 创建 toolbar
        const toolbar = E.createToolbar({
          editor,
          selector: "#editor-toolbar",
          config: toolbarConfig,
        });

        // 点击空白处 focus 编辑器
        document
          .getElementById("editor-text-area")
          .addEventListener("click", (e) => {
            if (e.target.id === "editor-text-area") {
              editor.blur();
              editor.focus(true); // focus 到末尾
            }
          });
      });
      function SubitArticle() {
        const article = JSON.parse(localStorage.getItem("article"));
        console.log(article);
        if (article.title == "") {
          ElMessage({
            type: "error",
            message: "文章标题不能为空",
          });
          return;
        }
        if (article.content == "") {
          ElMessage({
            type: "error",
            message: "文章内容不能为空",
          });
          return;
        }
        // 发送请求
        CreateArticle(article).then((res) => {
          ElMessage({
            message: "文章发布成功！",
            type: "success",
          });
          // 清空本地存储
          // 设置为空对象
          localStorage.setItem("article", JSON.stringify({}));
          // 跳转到文章列表
          setTimeout(() => {
            router.push("/news");
          }, 800);
        });
      }
      return {
        goBack,
        SubitArticle,
      };
    },
  };
</script>

<style scoped>
  html,
  body {
    background-color: #fff;
    height: 100%;
    overflow: hidden;
    color: #333;
  }

  #top-container {
    border-bottom: 1px solid #e8e8e8;
    height: 40px;
    padding: 0 30px;
  }

  #editor-toolbar {
    width: 1350px;
    background-color: #fcfcfc;
    margin: 0 auto;
  }

  #content {
    height: calc(100% - 40px);
    background-color: rgb(245, 245, 245);
    overflow-y: auto;
    position: relative;
  }

  #editor-container {
    width: 850px;
    margin: 30px auto 150px auto;
    background-color: #fff;
    padding: 20px 50px 50px 50px;
    border: 1px solid #e8e8e8;
    box-shadow: 0 2px 10px rgb(0 0 0 / 12%);
  }

  #title-container {
    padding: 20px 0;
    border-bottom: 1px solid #e8e8e8;
  }

  #title-container input {
    font-size: 30px;
    border: 0;
    outline: none;
    width: 100%;
    line-height: 1;
  }

  #editor-text-area {
    min-height: 900px;
    margin-top: 20px;
  }

  /* 删除功能按钮后平均分布 */
  .w-e-bar.w-e-bar-show.w-e-toolbar {
    justify-content: space-around;
  }

  #top-container p a {
    background-color: rgb(247, 107, 13);
    color: #fff;
    border: 0;
    border-radius: 4px;
    padding: 5px 15px;
    cursor: pointer;
  }

  #top-container p a:first-child {
    float: left;
  }

  #top-container p a:last-child {
    float: right;
  }

  #top-container p a:hover {
    opacity: 0.8;
  }
  /* D:\Users\san\Desktop\vite-pet-home\src\assets\css\wangedit.css */
</style>
